package com.yunyike.service.impl;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.yunyike.constants.CommonConstant;
import com.yunyike.constants.QuotationConstant;
import com.yunyike.dto.QuotationDTO;
import com.yunyike.exception.BusinessException;
import com.yunyike.mapper.QuotationMapper;
import com.yunyike.model.Quotation;
import com.yunyike.model.QuotationBrandMapping;
import com.yunyike.model.Supplier;
import com.yunyike.service.QuotationBrandMappingService;
import com.yunyike.service.QuotationService;
import com.yunyike.service.SupplierService;
import com.yunyike.utils.DateUtil;
import com.yunyike.utils.mybatis.PageBean;

@Transactional
@Service("quotationServiceImpl")
public class QuotationServiceImpl implements QuotationService{

	private Logger log = LoggerFactory.getLogger(QuotationServiceImpl.class);
	
	@Autowired
	private  QuotationMapper quotationMapper;
	
	@Autowired
	private SupplierService supplierService;
	
	@Autowired
	private QuotationBrandMappingService quotationBrandMappingService;

	public int deleteByPrimaryKey(String quotationId) {
		return quotationMapper.deleteByPrimaryKey(quotationId);
	}

	public int addQuotation(MultipartFile[] attachs, String fileUploadDirectory, Quotation record, String [] brand) {
		
		// 获取文件保存路径和文件保存名称
		String originalFilename = attachs[0].getOriginalFilename();
		String pathName = getPathName(fileUploadDirectory, originalFilename );
		
		// 保存供应单文件
		saveQuotationFile(attachs, pathName);
		
		int insert = 0;
		try {
			// 完善供应单其他信息
			String quotationId = saveOtherInfoByQuotation(attachs,pathName,record);
			// 保存供应单其他信息
			insert = quotationMapper.insert(record);
			log.info("quotationMapper.insert,result:{}",insert);
			
			if(insert != 1){
				throw new BusinessException("quotationMapper.insert failed.");
			}
			
			// 保存供应单品牌mapping信息
			insert = quotationBrandMappingService.save(brand, quotationId);
			log.info("quotationBrandMappingService.save,result:{}",insert);
			
		} catch (Exception e) {
			throw new BusinessException(e.getMessage(),e);
		} finally {
			if(insert != 1){
				throw new BusinessException("addQuotation failed.");
			}
		}
		
		return insert;
	}

	private String saveOtherInfoByQuotation(MultipartFile[] attachs, String pathName, Quotation record){
		String quotationId = UUID.randomUUID().toString();
		record.setQuotationId(quotationId);
		record.setQuotationName(attachs[0].getOriginalFilename().substring(0, attachs[0].getOriginalFilename().lastIndexOf(".")));
		record.setQuotationTime(new Date());
		record.setQuotationStatus(CommonConstant.NUMBER_1);
		record.setQuotationLink(pathName);
		
		return quotationId;
	}
	
	private void saveQuotationFile(MultipartFile[] attachs , String pathName){

		for (MultipartFile attach : attachs) {
			
			if(attach.isEmpty()){
				continue;
			}
			
			File file = new File(pathName);

			try {
				FileUtils.copyInputStreamToFile(attach.getInputStream(), file);
			} catch (IOException e) {
				throw new BusinessException("FileUtils.copyInputStreamToFile failed.message:"+e.getMessage(),e);
			}
		}
	}
	
	private String getPathName(String fileUploadDirectory, String originalFilename){
		
		int lastIndexOf = originalFilename.lastIndexOf(".");
		String fileName = originalFilename.substring(0,lastIndexOf);
		String fileSuffix = originalFilename.substring(lastIndexOf,originalFilename.length());
		
		StringBuffer sb = new StringBuffer();
		sb.append(fileUploadDirectory);
		sb.append("/").append(QuotationConstant.FILE_NAME_PREFIX);
		sb.append("_").append(fileName).append("_");
		sb.append(DateUtil.getCurDateStr("yyyy-MM-dd-hh-mm-ss"));
		sb.append(fileSuffix);
		
		String string = sb.toString();
		
		log.info("save file pathName:"+string);
		return string;
	}
	
	public int insertSelective(Quotation record) {
		return quotationMapper.insertSelective(record);
	}

	public Quotation selectByPrimaryKey(String quotationId) {
		return quotationMapper.selectByPrimaryKey(quotationId);
	}

	public int updateByPrimaryKeySelective(Quotation record) {
		return quotationMapper.updateByPrimaryKeySelective(record);
	}

	public int updateByPrimaryKey(Quotation record) {
		return quotationMapper.updateByPrimaryKey(record);
	}

	public List<Quotation> findAllQuotation() {
		return null;
	}

	public PageBean<QuotationDTO> findQuotationByCondition(PageBean<QuotationDTO> pageBean) {
		
		List<Quotation> list;
		try {
			list = quotationMapper.findQuotationListPageByCondition(pageBean);
		} catch (Exception e) {
			log.error("quotationMapper.findQuotationListPageByCondition failed.message:"+e.getMessage(),e);
			return null;
		}
		
		List<QuotationDTO> quotationDtoList = new ArrayList<QuotationDTO>();
		
		for (Quotation quotation : list) {
			QuotationDTO quotationDTO = new QuotationDTO();
			quotationDTO.setQuotation(quotation);
			
			quotationDtoList.add(quotationDTO);
		}
		
		// 完善供应单信息
		complateQuotations(quotationDtoList);
		
		pageBean.setResult(quotationDtoList);
		
		return pageBean;
	}
	
	private void complateQuotations(List<QuotationDTO> list){
		
		if(list == null || list.isEmpty()){
			return;
		}
		
		// 封装请求参数
		List<String> quotationIds = new ArrayList<String>();
		List<String> supplierIds = new ArrayList<String>();
		for (QuotationDTO quotationDTO : list) {
			
			Quotation quotation = quotationDTO.getQuotation();
			
			String quotationId = quotation.getQuotationId();
			quotationIds.add(quotationId);
			
			String supplierId = quotation.getSupplierId();
			supplierIds.add(supplierId);
		}
		
		// 请求
		Map<String, List<QuotationBrandMapping>> quotationBrandMap = quotationBrandMappingService.findQuotationBrandByQutationId(quotationIds);
		Map<String, Supplier> suppliersMap = supplierService.findSuppliersByIds(supplierIds);
		
		// 封装QuotationDTO
		for (QuotationDTO quotationDTO : list) {
			
			Quotation quotation = quotationDTO.getQuotation();
			
			String quotationId = quotation.getQuotationId();
			if(quotationBrandMap != null){
				List<QuotationBrandMapping> quotationBrandList = quotationBrandMap.get(quotationId);
				quotationDTO.setQuotationBrandList(quotationBrandList);
			}
			
			String supplierId = quotation.getSupplierId();
			Supplier supplier = suppliersMap.get(supplierId);
			if(supplier != null){
				quotation.setSupplierId(supplier.getSupplierName());
			}
		}
		
	}
}
